package com.danskin.wechat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.danskin.wechat.constant.DanskinConstants;
import com.danskin.wechat.dao.StoreInfoDao;
import com.danskin.wechat.dao.WxMediaPlatformDao;
import com.danskin.wechat.entity.SceneQrcode;
import com.danskin.wechat.entity.StoreInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.entity.example.StoreInfoExample;
import com.danskin.wechat.entity.example.StoreInfoExample.Criteria;
import com.danskin.wechat.entity.example.WxMediaPlatformExample;
import com.danskin.wechat.service.StoreInfoService;
import com.danskin.wechat.service.SysAreaService;
import com.danskin.wechat.service.WechatOpService;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.vo.StoreQrcodeScanVo;

@Service
public class StoreInfoServiceImpl implements StoreInfoService {

	@Autowired
	private StoreInfoDao storeInfoDao;

	@Autowired
	private WxMediaPlatformDao mpDao;

	@Autowired
	private WechatOpService wechatOpService;
	
	@Autowired
	private SysAreaService areaService;

	/**
	 * 根据主键获取门店信息
	 * 
	 * @param id
	 * @return
	 * @author makunsmac
	 */
	public StoreInfo selectByPrimaryKey(Integer id) {
		LogUtil.info("=======根据主键获取门店信息参数：id=" + id);

		StoreInfo storeInfo = new StoreInfo();

		try {
			storeInfo = storeInfoDao.selectByPrimaryKey(id);
		} catch (Exception e) {
			LogUtil.error("=======根据主键获取门店信息异常", e);
		}
		return storeInfo;
	}
	
	/**
     * 去重查询所有的店铺编号
     * @return
     * @author makunsmac
     */
    public List<String> selectStoreCodeList() {
    	List<String> storeCodeList = new ArrayList<String>();
    	
    	try {
    		storeCodeList = storeInfoDao.selectStoreCodeList();
		} catch (Exception e) {
			LogUtil.error("=======去重查询所有的店铺编号异常", e);
		}
    	return storeCodeList;
    }

	/**
	 * 分页查询店铺二维码扫描记录
	 * 
	 * @param param
	 * @return
	 * @author makunsmac
	 */
	public List<StoreQrcodeScanVo> listPageStoreQrcodeScan(Page page) {
		LogUtil.info("========分页查询店铺二维码扫描记录参数：" + ToStringBuilder.reflectionToString(page));

		List<StoreQrcodeScanVo> storeQrcodeScanList = new ArrayList<StoreQrcodeScanVo>();

		try {
			Map<String, Object> map = page.getMap();
			String paramStartTime = (String) map.get("paramStartTime");
			String paramEndTime = (String) map.get("paramEndTime");
			if (StringUtils.isNotEmpty(paramStartTime)) {
				map.put("newStartTime", paramStartTime + " " + "00:00:01");
			}
			if (StringUtils.isNotEmpty(paramEndTime)) {
				map.put("newTime", paramEndTime + " " + "23:59:59");
			}
			storeQrcodeScanList = storeInfoDao.listPageStoreQrcodeScan(page);
			//根据list中的省市区code获取省市区名称
			storeQrcodeScanList = getProvCityAndDistrict(storeQrcodeScanList);
		} catch (Exception e) {
			LogUtil.error("========查询店铺二维码扫描记录异常", e);
		}
		return storeQrcodeScanList;
	}
	
	/**
	 * 查询出所有符合条件的数据
	 * 
	 * @param param
	 * @return
	 * @author makunsmac
	 */
	public List<StoreQrcodeScanVo> selectStoreQrcodeScanList(StoreQrcodeScanVo param) {
		LogUtil.info("=======查询出所有符合条件的数据参数："+ToStringBuilder.reflectionToString(param));
		
		List<StoreQrcodeScanVo> scanList = new ArrayList<StoreQrcodeScanVo>();
		
		try {
			scanList = storeInfoDao.selectStoreQrcodeScanList(param);
			//根据list中的省市区code获取省市区名称
			scanList = getProvCityAndDistrict(scanList);
		} catch (Exception e) {
			LogUtil.error("==========查询出所有符合条件的数据异常", e);
		}
		return scanList;
	}
	
	/**
	 * 根据list中的省市区code获取省市区名称
	 * @param storeQrcodeScanList
	 * @return
	 * @author makunsmac
	 */
	private List<StoreQrcodeScanVo> getProvCityAndDistrict(List<StoreQrcodeScanVo> storeQrcodeScanList) {
		if(CollectionUtils.isNotEmpty(storeQrcodeScanList)) {
			for (StoreQrcodeScanVo temp : storeQrcodeScanList) {
				//根据省市区code查询对应的省市区名称
				String p = areaService.getSysAreaByCode(temp.getProvince());
				temp.setProvince(p);
				String c = areaService.getSysAreaByCode(temp.getCity());
				temp.setCity(c);
				String d = areaService.getSysAreaByCode(temp.getDistrict());
				temp.setDistrict(d);
			}
		}
		return storeQrcodeScanList;
	}

	/**
	 * 生成门店二维码
	 * 
	 * @param accessToken
	 * @param mpId
	 * @param storeInfo
	 * @return
	 * @author makunsmac
	 */
	public boolean createStoreQrCode(String accessToken, int mpId, StoreInfo storeInfo, String realPath) {
		int updateCount = 0;

		try {
			// 封装场景二维码
			SceneQrcode sceneQrcode = packageSceneQrcode(mpId, storeInfo);

			// 保存到场景二维码表中
			sceneQrcode = wechatOpService.saveSceneQrcode(accessToken, sceneQrcode, realPath);

			if (sceneQrcode == null || StringUtils.isBlank(sceneQrcode.getQrcodeUrl()) || sceneQrcode.getId() == null) {
				return false;
			}

			storeInfo.setQrcodeUrl(sceneQrcode.getQrcodeUrl());
			storeInfo.setSceneQrcodeId(sceneQrcode.getId());
			// 更新门店的二维码和场景二维码ID
			updateCount = updateByPrimaryKeySelective(storeInfo);
			if (updateCount > 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			LogUtil.error("======根据门店ID生成门店二维码异常", e);
		}
		return false;
	}
	
	/**
	 * 封装场景二维码
	 * 
	 * @param mpId
	 * @param storeInfo
	 * @return
	 * @author makunsmac
	 */
	private SceneQrcode packageSceneQrcode(int mpId, StoreInfo storeInfo) {
		SceneQrcode sceneQrcode = new SceneQrcode();
		sceneQrcode.setMpId(mpId);
		// 二维码类型设置成门店二维码
		sceneQrcode.setType(DanskinConstants.SCENE_QRCODE_TYPE_STORE_QRCODE);
		sceneQrcode.setName(storeInfo.getName());
		// limitType设置为1表示调用微信接口生成的二维码为永久二维码
		sceneQrcode.setLimitType(1);
		sceneQrcode.setSceneStr(storeInfo.getStoreCode());

		return sceneQrcode;
	}

	@Override
	public List<StoreInfo> getAllStoreByMpId(Integer mpId) {
		StoreInfoExample example = new StoreInfoExample();
		Criteria criteria = example.createCriteria();
		criteria.andMpIdEqualTo(mpId);
		List<StoreInfo> list = storeInfoDao.selectByExample(example);
		return list;
	}

	@Override
	public List<StoreInfo> listPageStrore(Page page) {
		List<StoreInfo> list = storeInfoDao.listPageStrore(page);
		return list;
	}

	@Override
	public List<StoreInfo> getStoreByCondition(StoreInfo store) {
		StoreInfoExample example = new StoreInfoExample();
		Criteria criteria = example.createCriteria();
		if (null != store.getProvince()) {
			criteria.andProvinceEqualTo(store.getProvince());
		}
		if (null != store.getCity()) {
			criteria.andCityEqualTo(store.getCity());
		}
		if (null != store.getMpId()) {
			criteria.andMpIdEqualTo(store.getMpId());
		}
		if (null != store.getType()) {
			criteria.andTypeEqualTo(store.getType());
		}
		List<StoreInfo> list = storeInfoDao.selectByExample(example);
		return list;
	}

	@Override
	public int updateByPrimaryKeySelective(StoreInfo store) {
		int i = storeInfoDao.updateByPrimaryKeySelective(store);
		return i;
	}

	@Override
	public int insertSelective(StoreInfo store, String appId) {
		WxMediaPlatformExample example = new WxMediaPlatformExample();
		com.danskin.wechat.entity.example.WxMediaPlatformExample.Criteria criteria = example.createCriteria();
		criteria.andAppIdEqualTo(appId);
		List<WxMediaPlatform> list = mpDao.selectByExample(example);
		int i = 0;
		if (list.size() > 0) {
			int mpId = list.get(0).getId();
			store.setMpId(mpId);
			store.setCreatedTime(new Date());
			i = storeInfoDao.insertSelective(store);
		}
		return i;
	}

	@Override
	public List<StoreQrcodeScanVo> queryStoreQrcodeScanVoExport(String storeCode, String eventType, String startTime,
			String endTime, String mpId) {
		if (StringUtils.isNotEmpty(startTime)) {
			startTime = startTime + " " + "00:00:01";
		}else{
			startTime = DateUtils.getStartTime() + " " + "00:00:01";
		}
		if (StringUtils.isNotEmpty(endTime)) {
			endTime = endTime + " " + "23:59:59";
		}else{
			endTime = DateUtils.getEndTime() + " " + "23:59:59";
		}
		return storeInfoDao.queryStoreQrcodeScanVoExport(storeCode,eventType,startTime,endTime,mpId);
	}
}
